$(function() {
	makeTree();
});

function makeTree() {
	var id = $("#id").val();
	$.post("/master/role/ress/" + id,function(json) {
		$('#treeRes').treeview({
			data: json,
			multiSelect: true,
			selectedBackColor: "#F1F2F7",
			selectedColor: "#2A3542",
			showCheckbox: false,
			onNodeSelected: function(event, data) {
				selectFun('treeRes', data);
			},
			onNodeUnselected: function(event, data) {
				unselect('treeRes', data);
			}
		});
		$('#treeRes').treeview('expandAll', {
			levels: 2,
			silent: true
		});
	});
}

function setRessValue() {
	var s = getValue('treeRes');
	$("#s").val(s);
}
//取值
function getValue(id) {
	var ns = $('#' + id).treeview('getSelected');
	var v = '';
	$.each(ns,function(i, d) {
		v += d.id + ',';
	});
	if (v.length > 0) {
		v = v.substring(0, v.length - 1);
	}
	return v;
}

//start 选中函数
function selectFun(id, data) {
	selectPFun(id, data);
	$('#' + id).treeview('selectNode', [data.nodeId, {
		silent: true
	}]);
	if (data.nodes.length > 0) {
		$.each(data.nodes,function(i, d) {
			$('#' + id).treeview('selectNode', [d.nodeId, {
				silent: true
			}]);
			try {
				selectFun(id, d);
			} catch(e) {}
		});
	}
}

function unselect(id, data) {
	unselectP(id, data);
	$('#' + id).treeview('unselectNode', [data.nodeId, {
		silent: true
	}]);
	if (data.nodes.length > 0) {
		$.each(data.nodes,function(i, d) {
			$('#' + id).treeview('unselectNode', [d.nodeId, {
				silent: true
			}]);
			try {
				unselect(id, d);
			} catch(e) {}
		});
	}
}

function selectPFun(id, data) {
	try {
		var n = $('#' + id).treeview('getParent', data);
		$('#' + id).treeview('selectNode', [n.nodeId, {
			silent: true
		}]);
		selectPFun(id, n);
	} catch(e) {}
}

function unselectP(id, data) {
	try {
		var n = $('#' + id).treeview('getParent', data);
		var ss = $('#' + id).treeview('getSelected', data);
		//子循环
		var b = true;
		$.each(ss,function(j, d2) {
			$.each(n.nodes,
			function(i, d) {
				if (d.nodeId == d2.nodeId) {
					b = false;
				}
			});
		});

		if (b) {
			$('#' + id).treeview('unselectNode', [n.nodeId, {
				silent: true
			}]);
		}
		unselectP(id, n);
	} catch(e) {}
}